import React from "react"
import {
	Form,
	Input,
	Button,
	message,
	Select,
	DatePicker,
	Upload,
	Icon
} from "antd"
const FormItem = Form.Item
const Option = Select.Option
import BreadCrumb from "@/view/comps/breadcrub/breadcrub"
import { getUrlParam } from "@/util/util"
import "./article.less"

const FORMINPUT = {
	labelCol: { span: 4 },
	wrapperCol: { span: 18 }
}
const FORMINPUT2 = {
	labelCol: { span: 4 },
	wrapperCol: { span: 6 }
}
const FORMBUTTONN = {
	labelCol: { span: 4 },
	wrapperCol: { span: 8, offset: 4 }
}
const COMPLETESTATUS = [
	{ name: "未完成", value: "1" },
	{ name: "已完成", value: "2" }
]

export default class AddArticle extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			title: "",
			subTitle: "",
			tagList: [],
			classifyList: [],
			tag: undefined,
			classify: undefined,
			completeS: COMPLETESTATUS[0].value,
			imageUrl: ""
		}
		this.id = getUrlParam("id")
	}
	componentDidMount() {
		this.getUploadToken() // 需要处理页面请求先后关系
		this.getTagList()
		this.getClassify()
		if (this.id) {
			this.getArticleDetail()
		} else {
			this.initMarkdown()
		}
	}
	// 获取文章详情
	getArticleDetail = () => {
		AJAX({
			url: "/findArticleList",
			data: { _id: this.id }
		}).then(
			res => {
				let article = res.data[0] || {}
				this.initPage(article)
			},
			err => message.error(err.msg)
		)
	}

	initPage = data => {
		this.setState({
			title: data.title,
			subTitle: data.subTitle,
			tag: data.tag,
			classify: data.classify,
			imageUrl: data.coverImg
		})
		this.initMarkdown(data.originText)
	}
	getTagList = () => {
		AJAX({
			url: "/findTag",
			data: {}
		}).then(
			res => {
				const list = res.data || []
				this.setState({ tagList: list })
			},
			err => message.error(err.msg)
		)
	}
	getClassify = () => {
		AJAX({
			url: "/findClassify",
			data: {}
		}).then(
			res => {
				const list = res.data || []
				this.setState({ classifyList: list })
			},
			err => message.error(err.msg)
		)
	}

	handleChange = info => {
		if (info.file.status === "uploading") {
			this.setState({ loading: true })
			return
		}
		if (info.file.status === "done") {
			console.log(info)
			const imageUrl =
				"http://pcb7ukio1.bkt.clouddn.com/" + info.file.response.key
			this.setState({
				loading: false,
				imageUrl
			})
		}
	}

	getUploadToken = () => {
		AJAX({
			method: "post",
			url: "/getUploadKey",
			data: {}
		})
			.then(res => {
				if (res.errNo == 0) {
					this.setState({ token: res.data })
				}
			})
			.catch(err => console.log(err))
	}

	initMarkdown = (value = "") => {
		const textarea = document.getElementById("m-editor")
		this.mditor = Mditor.fromTextarea(textarea)
		this.mditor.value = value
		this.mditor.on("ready", function() {
			console.log("ready方法执行了...")
		})
	}
	getReqParam = () => {
		const {
			title,
			subTitle,
			tag,
			classify,
			completeS,
			imageUrl
		} = this.state
		return {
			title,
			subTitle,
			tag,
			classify,
			status: completeS,
			coverImg: imageUrl
		}
	}
	createArticle = () => {
		const reqParam = this.getReqParam()
		console.log(this.mditor.viewer)
		console.log(this.mditor.viewer.html)
		const param = {
			...reqParam,
			text: this.mditor.viewer.html,
			originText: this.mditor.viewer.value
		}
		AJAX({
			method: "post",
			url: "/createArticle",
			data: param
		})
			.then(res => {
				if (res.errNo == 0) {
					message.success("创建成功")
					this.setState({ token: res.data })
				}
			})
			.catch(err => console.log(err))
	}

	render() {
		const { title, subTitle, tagList, classifyList, imageUrl } = this.state

		const uploadButton = (
			<div>
				<Icon type={this.state.loading ? "loading" : "plus"} />
				<div className="ant-upload-text">Upload</div>
			</div>
		)
		return (
			<div>
				<BreadCrumb
					bread={[
						{ title: "Dashboard", link: "/" },
						{ title: "新增博客文章" }
					]}
				/>
				<div className="page-container article-less">
					<div className="form-control">
						<Form>
							<FormItem
								{...FORMINPUT}
								label="标题"
								required={true}
							>
								<Input
									size="large"
									value={title}
									onChange={e =>
										this.setState({ title: e.target.value })
									}
									placeholder="请输入名称"
								/>
							</FormItem>

							<FormItem {...FORMINPUT} label="副标题">
								<Input
									size="large"
									value={subTitle}
									ref={ref => (this.pwdRef = ref)}
									onChange={e =>
										this.setState({
											subTitle: e.target.value
										})
									}
									placeholder="请输入标签描述"
								/>
							</FormItem>
							<div className="article-status">
								<FormItem
									{...FORMINPUT2}
									label="标签"
									required={true}
								>
									<Select
										size="large"
										showSearch
										placeholder="请选择标签"
										optionFilterProp="children"
										value={this.state.tag}
										onChange={value =>
											this.setState({ tag: value })
										}
									>
										{tagList.map(item => (
											<Option key={item.name}>
												{item.name}
											</Option>
										))}
									</Select>
								</FormItem>
								<FormItem
									{...FORMINPUT2}
									label="分类"
									required={true}
								>
									<Select
										size="large"
										showSearch
										placeholder="请选择分类"
										optionFilterProp="children"
										value={this.state.classify}
										onChange={value =>
											this.setState({ classify: value })
										}
									>
										{classifyList.map(item => (
											<Option key={item.name}>
												{item.name}
											</Option>
										))}
									</Select>
								</FormItem>
								<FormItem
									{...FORMINPUT2}
									label="完成状态"
									required={true}
								>
									<Select
										size="large"
										showSearch
										placeholder="请选择完成状态"
										value={this.state.completeS}
										optionFilterProp="children" // 不太懂其意义
										onChange={value =>
											this.setState({ completeS: value })
										}
									>
										{COMPLETESTATUS.map(item => (
											<Option key={item.value}>
												{item.name}
											</Option>
										))}
									</Select>
								</FormItem>
								{/* <FormItem {...FORMINPUT2} label="创建时间">
									<DatePicker
										className="wd-250"
										format="YYYY-MM-DD HH:mm:ss"
										size="large"
										showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
										value={this.state.createTime}
										onChange={value => this.setState({createTime: value})}
									/>
								</FormItem> */}
								<div className="img-cover">
									<Upload
										className="upload-cover"
										name="file"
										listType="picture-card"
										showUploadList={false}
										action="http://up.qiniu.com"
										beforeUpload={this.beforeUpload}
										data={{ token: this.state.token }}
										onChange={this.handleChange}
									>
										{imageUrl ? (
											<img
												src={imageUrl}
												className="img-cover-item"
											/>
										) : (
											uploadButton
										)}
									</Upload>
									<p className="ml-10">上传封面</p>
								</div>
							</div>
							<FormItem>
								<textarea name="editor" id="m-editor" />
							</FormItem>

							<FormItem className="mt-20" {...FORMBUTTONN}>
								<Button
									type="primary"
									onClick={this.createArticle}
								>
									添加博客
								</Button>
							</FormItem>
						</Form>
					</div>
				</div>
			</div>
		)
	}
}
